//
//  MLExpression.swift
//  ExpressionDemo
//
//  Created by aby on 2018/8/6.
//  Copyright © 2018 aby. All rights reserved.
//

import Foundation
import UIKit

class MLExpression {
    var regex: String = ""
    var plistName: String = ""
    var bundleName: String = ""
    
    private var expressionRegularExpression: NSRegularExpression?
    lazy var expressionMap: NSDictionary = {
        if plistName == "" {
            return NSDictionary.init()
        }
        if !plistName.lowercased().hasSuffix(".plist") {
            plistName.append(".plist")
        }
        let dic = NSDictionary.init(contentsOfFile: (Bundle.main.resourcePath?.appending("/\(plistName)"))!)
        return dic ?? NSDictionary.init()
    }()
    
    init(regex: String, plistName: String, bundleName: String) {
        self.regex = regex
        self.plistName = plistName
        self.bundleName = bundleName
    }
    
    
    
    func expressionAttributedString(string: String) -> NSAttributedString {
        let target: NSMutableAttributedString = NSMutableAttributedString.init(string: string)
        if target.length <= 0 {
            return target
        }
        do {
            try self.expressionRegularExpression = NSRegularExpression.init(pattern: regex, options: .caseInsensitive)
        } catch {
            self.expressionRegularExpression = nil
            print(error)
        }
        guard let expressionRegular = self.expressionRegularExpression else { return target }
        let tempAttribute = NSMutableAttributedString.init()
        // 处理表情
        let resArr = expressionRegular.matches(in: target.string, options: .withTransparentBounds, range: NSRange.init(location: 0, length: target.length))
        var location: Int = 0;
        for resultText: NSTextCheckingResult in resArr {
            let range: NSRange = resultText.range
            let subString: NSAttributedString = target.attributedSubstring(from: NSRange.init(location: location, length: range.location - location))
            // 先把非表情部分加上去
            tempAttribute.append(subString)
            // 修改location 的值，从下一个表情的位置开始
            location = NSMaxRange(range)
            
            let expressionStr = target.attributedSubstring(from: range)
            let imageName: String = self.expressionMap.object(forKey: expressionStr.string) as? String ?? ""
            // 如果图片名存在
            if imageName.count > 0 {
                let bundle = Bundle.init(url: Bundle.main.url(forResource: bundleName, withExtension: ".bundle")!)
                let image: UIImage = UIImage.init(named: imageName, in: bundle!, compatibleWith: nil)!
                let attachment = NSTextAttachment.init()
                attachment.image = image
                attachment.bounds = CGRect.init(x: 0, y: 0, width: 20, height: 16)
                let attachmentString: NSMutableAttributedString = NSAttributedString.init(attachment: attachment).mutableCopy() as! NSMutableAttributedString
                expressionStr.enumerateAttributes(in: NSRange.init(location: 0, length: expressionStr.length), options: .longestEffectiveRangeNotRequired) { (attrs, range, stop) in
                    if attrs.count>0 && range.length==expressionStr.length {
                        attachmentString.addAttributes(attrs, range: NSRange.init(location: 0, length: attachmentString.length))
                    }
                }
                tempAttribute.append(attachmentString)
            } else {
                tempAttribute.append(expressionStr)
            }
        }
        if location < target.length {
            let range = NSRange.init(location: location, length: target.length - location)
            let sub = target.attributedSubstring(from: range)
            tempAttribute.append(sub)
        }
        return tempAttribute
    }
}
